package com.cskaoyan.servlet;

import com.cskaoyan.bean.MarketStorage;
import com.cskaoyan.bean.common.BaseRespVo;
import com.cskaoyan.service.AdminStorageService;
import com.cskaoyan.service.AdminStorageServletImpl;
import com.cskaoyan.util.JacksonUtil;
import com.cskaoyan.util.ResponseUtil;
import lombok.SneakyThrows;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.IOException;
import java.io.InputStream;

@WebServlet("/admin/storage/*")
@MultipartConfig
public class AdminStorageServlet extends WdBaseServlet {
    private AdminStorageService storageService = new AdminStorageServletImpl();

    private void create(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        Part filePart = request.getPart("file");
        InputStream inputStream = filePart.getInputStream();
        String originFileName = filePart.getSubmittedFileName();
        MarketStorage marketStorage = storageService.store(inputStream, filePart.getSize(),
                filePart.getContentType(), originFileName);
        ResponseUtil.responseOkJsonVo(response, marketStorage);
    }
    private BaseRespVo list(HttpServletRequest request, HttpServletResponse response){
        String pageStr = request.getParameter("page");
        String oder = request.getParameter("order");
        Integer page = Integer.parseInt(pageStr);
        String limitStr = request.getParameter("limit");
        Integer limit = Integer.parseInt(limitStr);
        String sort = request.getParameter("sort");


        BaseRespVo baseRespVo = storageService.list(request);

        return baseRespVo;
    }
    @SneakyThrows
    private BaseRespVo update(HttpServletRequest request, HttpServletResponse response){
        String s = request.getReader().readLine();
        MarketStorage marketStorage = JacksonUtil.read(s, MarketStorage.class);

        BaseRespVo baseRespVo = storageService.update(marketStorage);

        return baseRespVo;
    }
    @SneakyThrows
    private BaseRespVo delete(HttpServletRequest request, HttpServletResponse response){
        String s = request.getReader().readLine();
        MarketStorage marketStorage = JacksonUtil.read(s, MarketStorage.class);

        BaseRespVo baseRespVo = storageService.delete(marketStorage);

        return baseRespVo;
    }
}